const db = require('../model/db');

// 创建订单
const createOrder = (req, res) => {
    const userId = req.user.id;
    const { cart_items } = req.body;
    console.log('Create order request received:', { userId, cart_items }); // 添加日志

    if (!cart_items || !Array.isArray(cart_items) || cart_items.length === 0) {
        console.error('Invalid or empty cart_items array received:', cart_items); // 添加日志
        return res.status(400).json({ error: '购物车为空' });
    }

    // 开始事务
    db.serialize(() => {
        db.run('BEGIN TRANSACTION', (beginTransactionErr) => {
             if (beginTransactionErr) {
                 console.error('Failed to begin transaction:', beginTransactionErr);
                 return res.status(500).json({ error: '创建订单失败' });
             }

            try {
                // 1. 获取购物车项详情并计算总价
                const getCartItems = new Promise((resolve, reject) => {
                    const placeholders = cart_items.map(() => '?').join(',');
                    const query = `
                        SELECT 
                            ci.*,
                            p.price as product_price,
                            p.stock as product_stock,
                            p.status as product_status,
                            pt.price as pet_price,
                            pt.status as pet_status
                        FROM cart_items ci
                        LEFT JOIN products p ON ci.product_id = p.id
                        LEFT JOIN pets pt ON ci.pet_id = pt.id
                        WHERE ci.id IN (${placeholders}) AND ci.user_id = ?
                    `;
                    const params = [...cart_items, userId];
                    console.log('Executing get cart items query:', query); // 添加日志
                    console.log('With params:', params); // 添加日志

                    db.all(query, params, (err, items) => {
                        if (err) {
                            console.error('Database error fetching cart items:', err); // 添加日志
                            reject(err);
                        }
                        if (!items || items.length === 0) {
                             console.error('No cart items found for IDs:', cart_items); // 添加日志
                            reject(new Error('部分购物车项不存在或不属于当前用户'));
                         }
                        if (items.length !== cart_items.length) {
                             console.warn('Mismatch between requested cart item IDs and items found:', { requested: cart_items.length, found: items.length }); // 添加日志
                            reject(new Error('部分购物车项不存在或不属于当前用户'));
                        }
                        console.log('Fetched cart items from DB:', items); // 添加日志
                        resolve(items);
                    });
                });

                getCartItems.then(items => {
                    console.log('Successfully fetched cart items, proceeding with order creation.'); // 添加日志
                    // 2. 验证商品状态和库存
                    const invalidItems = items.filter(item => {
                        if (item.product_id) {
                            return item.product_status !== 'active' || item.product_stock < item.quantity;
                        } else if (item.pet_id) {
                             return item.pet_status !== 'available';
                         } else { // Should not happen with correct data/schema, but handle defensively
                             console.warn('Cart item without product_id or pet_id during validation:', item); // 添加日志
                             return true; // Consider invalid
                         }
                    });

                    if (invalidItems.length > 0) {
                         console.error('Invalid items found during validation:', invalidItems); // 添加日志
                        // Note: The error message '部分商品已下架或库存不足' is returned by the catch block below
                        throw new Error('部分商品已下架或库存不足');
                    }
                    console.log('Item validation passed.'); // 添加日志

                    // 3. 计算总价
                    const totalAmount = items.reduce((sum, item) => {
                        const price = item.product_id ? item.product_price : item.pet_price;
                        return sum + price * item.quantity;
                    }, 0);
                    console.log('Calculated total amount:', totalAmount); // 添加日志

                    // 4. 创建订单
                    db.run(
                        'INSERT INTO orders (user_id, total_amount, status) VALUES (?, ?, ?)',
                        [userId, totalAmount, 'pending'],
                        function(err) {
                            if (err) {
                                console.error('Database error creating order:', err); // 添加日志
                                throw err; // This will be caught by the outer catch block
                            }
                            const orderId = this.lastID;
                            console.log('Order created with ID:', orderId); // 添加日志

                            // 5. 创建订单项
                            const orderItemsPromises = items.map(item => {
                                return new Promise((resolve, reject) => {
                                    const price = item.product_id ? item.product_price : item.pet_price;
                                    const insertItemQuery = `INSERT INTO order_items (order_id, product_id, pet_id, quantity, price)
                                         VALUES (?, ?, ?, ?, ?)`;
                                    const insertItemParams = [orderId, item.product_id, item.pet_id, item.quantity, price];
                                     console.log('Executing insert order item query:', insertItemQuery); // 添加日志
                                     console.log('With params:', insertItemParams); // 添加日志
                                    db.run(
                                        insertItemQuery,
                                        insertItemParams,
                                        (err) => {
                                            if (err) {
                                                console.error('Database error creating order item:', err); // 添加日志
                                                reject(err);
                                            }
                                            console.log('Order item inserted:', item.id); // 添加日志
                                            resolve();
                                        }
                                    );
                                });
                            });

                            // 6. 更新商品库存和状态
                            const updateItemsPromises = items.map(item => {
                                return new Promise((resolve, reject) => {
                                    if (item.product_id) {
                                        // 更新商品库存
                                        const updateProductQuery = 'UPDATE products SET stock = stock - ? WHERE id = ?';
                                        const updateProductParams = [item.quantity, item.product_id];
                                         console.log('Executing update product query:', updateProductQuery); // 添加日志
                                         console.log('With params:', updateProductParams); // 添加日志
                                        db.run(
                                            updateProductQuery,
                                            updateProductParams,
                                            (err) => {
                                                if (err) {
                                                    console.error('Database error updating product stock:', err); // 添加日志
                                                    reject(err);
                                                }
                                                console.log('Product stock updated:', item.product_id); // 添加日志
                                                resolve();
                                            }
                                        );
                                    } else if (item.pet_id) {
                                        // 更新宠物状态
                                        const updatePetQuery = 'UPDATE pets SET status = "sold" WHERE id = ?';
                                        const updatePetParams = [item.pet_id];
                                         console.log('Executing update pet query:', updatePetQuery); // 添加日志
                                         console.log('With params:', updatePetParams); // 添加日志
                                        db.run(
                                            updatePetQuery,
                                            updatePetParams,
                                            (err) => {
                                                if (err) {
                                                    console.error('Database error updating pet status:', err); // 添加日志
                                                    reject(err);
                                                }
                                                console.log('Pet status updated:', item.pet_id); // 添加日志
                                                resolve();
                                            }
                                        );
                                    } else {
                                         console.warn('Item without product_id or pet_id during update:', item); // 添加日志
                                         resolve(); // Nothing to update for this item
                                     }
                                });
                            });

                            // 7. 删除购物车项
                            const deleteCartItemsPromise = new Promise((resolve, reject) => {
                                const placeholders = cart_items.map(() => '?').join(',');
                                const deleteQuery = `DELETE FROM cart_items WHERE id IN (${placeholders}) AND user_id = ?`;
                                const deleteParams = [...cart_items, userId];
                                 console.log('Executing delete cart items query:', deleteQuery); // 添加日志
                                 console.log('With params:', deleteParams); // 添加日志
                                db.run(
                                    deleteQuery,
                                    deleteParams,
                                    (err) => {
                                        if (err) {
                                            console.error('Database error deleting cart items:', err); // 添加日志
                                            reject(err);
                                        }
                                        console.log('Cart items deleted:', cart_items); // 添加日志
                                        resolve();
                                    }
                                );
                            });

                            // 执行所有操作
                            Promise.all([
                                ...orderItemsPromises,
                                ...updateItemsPromises,
                                deleteCartItemsPromise
                            ])
                                .then(() => {
                                    db.run('COMMIT', (err) => {
                                        if (err) {
                                            console.error('Failed to commit transaction:', err); // 添加日志
                                            // 尝试回滚以清理
                                            db.run('ROLLBACK', (rollbackErr) => {
                                                 if (rollbackErr) console.error('Failed to rollback transaction:', rollbackErr); // 添加日志
                                            });
                                            return res.status(500).json({ error: '提交订单时发生错误' });
                                        }
                                        console.log('Transaction committed successfully.'); // 添加日志
                                        // 事务成功，发送响应给客户端，包含新创建的订单ID
                                        res.status(201).json({ id: orderId, message: '订单创建成功！' });
                                    });
                                })
                                .catch(err => {
                                    console.error('Error during order creation process:', err); // 添加日志
                                    // 操作失败，回滚事务
                                    db.run('ROLLBACK', (rollbackErr) => {
                                        if (rollbackErr) console.error('Failed to rollback transaction:', rollbackErr); // 添加日志
                                    });
                                    // 根据错误类型发送不同的响应
                                    if (err.message === '部分商品已下架或库存不足') {
                                         res.status(400).json({ error: err.message });
                                    } else if (err.message === '部分购物车项不存在或不属于当前用户') {
                                         res.status(400).json({ error: err.message });
                                    } else {
                                        res.status(500).json({ error: '创建订单失败' });
                                    }
                                });
                        }
                    );
                })
                .catch(err => {
                    console.error('Error fetching cart items or validation failed:', err); // 添加日志
                     db.run('ROLLBACK', (rollbackErr) => {
                         if (rollbackErr) console.error('Failed to rollback transaction:', rollbackErr); // 添加日志
                     });
                     // 根据错误类型发送不同的响应
                     if (err.message === '部分购物车项不存在或不属于当前用户') {
                          res.status(400).json({ error: err.message });
                     } else if (err.message === '部分商品已下架或库存不足') {
                         res.status(400).json({ error: err.message });
                     } else {
                         res.status(500).json({ error: '创建订单失败' });
                     }
                });

            } catch (err) {
                 console.error('Unexpected error in createOrder transaction:', err); // 添加日志
                 db.run('ROLLBACK', (rollbackErr) => {
                     if (rollbackErr) console.error('Failed to rollback transaction:', rollbackErr); // 添加日志
                 });
                 res.status(500).json({ error: '创建订单失败' });
             }
        });
    });
};

// 获取订单列表
const getOrders = (req, res) => {
    const userId = req.user.id;
    console.log('Getting orders for user:', userId); // 添加日志

    const { status, page = 1, limit = 10 } = req.query;
    console.log('Query params:', { status, page, limit }); // 添加日志
    
    let query = `
        SELECT o.*, u.username 
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.id
        WHERE o.user_id = ?
    `;
    let params = [userId];

    if (status) {
        query += ' AND o.status = ?';
        params.push(status);
    }

    query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?';
    const offset = (page - 1) * limit;
    params.push(limit, offset);

    console.log('Executing query:', query); // 添加日志
    console.log('With params:', params); // 添加日志

    db.all(query, params, (err, orders) => {
        if (err) {
            console.error('Failed to get orders:', err); // 添加日志
            return res.status(500).json({ error: '获取订单列表失败' });
        }

        console.log('Orders found:', orders); // 添加日志

        // 获取总数
        let countQuery = 'SELECT COUNT(*) as total FROM orders WHERE user_id = ?';
        const countParams = [userId];
        if (status) {
            countQuery += ' AND status = ?';
            countParams.push(status);
        }

        console.log('Executing count query:', countQuery); // 添加日志
        console.log('With params:', countParams); // 添加日志

        db.get(countQuery, countParams, (err, result) => {
            if (err) {
                console.error('Failed to get order count:', err); // 添加日志
                return res.status(500).json({ error: '获取订单总数失败' });
            }

            console.log('Total orders:', result.total); // 添加日志

            res.json({
                total: result.total,
                page: parseInt(page),
                limit: parseInt(limit),
                data: orders
            });
        });
    });
};

// 获取订单详情
const getOrderById = (req, res) => {
    const userId = req.user.id;
    const { id } = req.params;
    console.log('Getting order details for order ID:', id, 'user ID:', userId); // 添加日志

    // 查询订单基本信息
    const orderQuery = `
        SELECT o.*, u.username 
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.id
        WHERE o.id = ? AND (o.user_id = ? OR ? IN (
            SELECT user_id FROM users WHERE role = 'admin'
        ))
    `;
    const orderParams = [id, userId, userId];
    console.log('Executing order query:', orderQuery); // 添加日志
    console.log('With params:', orderParams); // 添加日志

    db.get(orderQuery, orderParams, (err, order) => {
        if (err) {
            console.error('Database error fetching order:', err); // 添加日志
            return res.status(500).json({ error: '获取订单详情失败' });
        }
        if (!order) {
            console.warn('Order not found for ID:', id, 'user ID:', userId); // 添加日志
            return res.status(404).json({ error: '订单不存在或无权访问' }); // 修改错误信息以更明确
        }

        console.log('Order found:', order); // 添加日志

        // 获取订单项
        const itemsQuery = `
            SELECT 
                oi.*,
                p.name as product_name,
                p.image_url as product_image,
                pt.name as pet_name,
                pt.image_url as pet_image
            FROM order_items oi
            LEFT JOIN products p ON oi.product_id = p.id
            LEFT JOIN pets pt ON oi.pet_id = pt.id
            WHERE oi.order_id = ?
        `;
        const itemsParams = [id];
        console.log('Executing order items query:', itemsQuery); // 添加日志
        console.log('With params:', itemsParams); // 添加日志

        db.all(itemsQuery, itemsParams, (err, items) => {
            if (err) {
                console.error('Database error fetching order items:', err); // 添加日志
                return res.status(500).json({ error: '获取订单项失败' });
            }

            console.log('Order items found:', items); // 添加日志

            // 处理订单项数据格式
            const processedItems = items.map(item => {
                if (item.product_id) {
                    return {
                        id: item.id,
                        quantity: item.quantity,
                        price: item.price, // 订单项中应该存储了当时的价格
                        item: {
                            type: 'product',
                            id: item.product_id,
                            name: item.product_name,
                            image_url: item.product_image,
                             // Note: price is from order_items, not products
                        }
                    };
                } else if (item.pet_id) {
                    return {
                         id: item.id,
                         quantity: item.quantity,
                         price: item.price, // 订单项中应该存储了当时的价格
                        item: {
                            type: 'pet',
                            id: item.pet_id,
                            name: item.pet_name,
                            image_url: item.pet_image,
                            // Note: price is from order_items, not pets
                        }
                    };
                }
                console.warn('Order item without product_id or pet_id:', item); // 添加日志
                return null; // Skip items with no associated product or pet
            }).filter(item => item !== null); // 过滤掉无效的订单项

            console.log('Processed order items:', processedItems); // 添加日志

            // 将订单基本信息和订单项组合返回
            const fullOrderDetails = {
                ...order,
                items: processedItems
            };

            console.log('Returning full order details:', fullOrderDetails); // 添加日志
            res.json(fullOrderDetails);
        });
    });
};

// 更新订单状态
const updateOrderStatus = (req, res) => {
    const { id } = req.params;
    const { status } = req.body;
    const userId = req.user.id;

    const validStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
        return res.status(400).json({ error: '无效的订单状态' });
    }

    // 检查权限（只有管理员或订单所有者可以更新）
    const checkPermission = new Promise((resolve, reject) => {
        db.get(
            'SELECT user_id FROM orders WHERE id = ?',
            [id],
            (err, order) => {
                if (err) reject(err);
                if (!order) reject(new Error('订单不存在'));

                db.get(
                    'SELECT role FROM users WHERE id = ?',
                    [userId],
                    (err, user) => {
                        if (err) reject(err);
                        if (user.role === 'admin' || order.user_id === userId) {
                            resolve();
                        } else {
                            reject(new Error('没有权限更新此订单'));
                        }
                    }
                );
            }
        );
    });

    checkPermission
        .then(() => {
            db.run(
                'UPDATE orders SET status = ? WHERE id = ?',
                [status, id],
                function(err) {
                    if (err) {
                        return res.status(500).json({ error: '更新订单状态失败' });
                    }
                    if (this.changes === 0) {
                        return res.status(404).json({ error: '订单不存在' });
                    }
                    res.json({ message: '订单状态更新成功' });
                }
            );
        })
        .catch(error => {
            res.status(403).json({ error: error.message });
        });
};

module.exports = {
    createOrder,
    getOrders,
    getOrderById,
    updateOrderStatus
}; 